<template>
  <div class="single">
    <div class="frame">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="题干：" prop="input">
          <el-input v-model="ruleForm.input"></el-input>
        </el-form-item>
        <!-- <el-form-item label="作者：" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item> -->
        <el-form-item label="知识点：" prop="knowledge">
          <el-cascader v-model="valuename" :options="options" @change="handleChange"> </el-cascader>
        </el-form-item>
        <el-form-item label="分数：" prop="numm">
          <el-input-number v-model="num" :precision="2" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <div class="difficulty">
            <el-rate v-model="value1"></el-rate>
          </div>
        </el-form-item>
        <el-form-item label="预览：">
          <div class="preview">
            <div class="title">题目预览：</div>
            <div class="text">
              <div>题目预览 - 题面描述及答案（答题者只可查看题面描述）</div>
             <div v-html="`${md(ruleForm.input)}`"></div>
              <div v-for="(domain, index) in ruleForm.domains" :key="domain.key">
                <div>
                  <span class="valuee"> {{ letter[index] }}</span>
                  <span class="value"> {{ domain.value }}</span>
                </div>
              </div>
              <div>
                <span>答案：</span>
                <span>[{{ ruleForm.label }}]</span>
              </div>
              <div>
                <span>分数：</span>
                <span>{{ num }}</span>
              </div>
              <div>
                <span>知识点：</span>
                <span>{{ knowledges }}</span>
              </div>
              <div class="level">
                <span>难度：</span>
                <span>
                  <el-rate v-model="value1" disabled="disabled"></el-rate>
                </span>
              </div>
              <div class="analysis">
                <span>解析：</span>
                <span>{{ ruleForm.analysis }}</span>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="题面：">
          <mavon-editor ref="md" id="editor" v-model="ruleForm.input" :toolbars="toolbars" defaultOpen="fasle"> </mavon-editor>
        </el-form-item>

        <el-form-item label="选项：" :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-dynamic" prop="option">
          <div v-for="(domain, index) in ruleForm.domains" :key="domain.key" class="options">
            <div>
              <span class="spann">{{ letter[index] }}</span>
              <span class="span">{{ letter[index] }}</span>
              <el-input class="input" v-model="domain.value"></el-input>
              <el-button type="danger" icon="el-icon-delete" class="button" @click.prevent="removeDomain(domain)"></el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="答案：" prop="type">
          <el-radio-group v-model="checkedCities" class="checkedCities">
            <el-radio v-for="(city, index) in ruleForm.domains" @change="type(letter[index])" :label="letter[index]" :key="city.key" name="type">
              <!-- <span @click="type(letter[index])" class="typess">
                {{ letter[index] }}
              </span> -->
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="解析：" prop="inputss">
          <el-input type="textarea" v-model="ruleForm.analysis" rows="3"></el-input>
        </el-form-item>

        <el-form-item>
		  <el-button style="background-color:#03d3bd;color: white;" size="medium" @click="submitForm('ruleForm')" >添加</el-button>
		  <el-button style="border: #dcdcdc 1px solid;color: #000000;"　size="medium" @click="resetForm('ruleForm')">重置</el-button>
		  <el-button style="background-color: #ffab03;color: white;"　size="medium" @click="addDomain">新增选项</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import marked from "marked";
import hljs from 'highlight.js'
import javascript from 'highlight.js/lib/languages/javascript'
import 'highlight.js/styles/monokai-sublime.css'
import {
		TestManager
	} from '../../request/test.js'
var token=window.localStorage.getItem("token");
export default {
  name: 'SingleCom',
  data() {
    return {
      value1: null,
      num: 1,
      checkedCities: [],
      letter: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'R', 'J', 'K', 'L'],
      centerDialogVisible: false,
      ruleForm: {
        domains: [
          {
            value: '替换为错误项'
          },
          {
            value: '替换为错误项'
          },
          {
            value: '替换为错误项'
          },
          {
            value: '替换为错误项'
          }
        ],
        knowledge: [],
        name: '',
        data: '',
        input: '这是一个单选题的样例。答案为C，分值为2分。(2分)',
        analysis: '',
        delivery: false,
        type: [],
        resource: '',
        desc: '',
        label: '',
        single: {
          answer: '',
          content: '',
          createTime: '',
          difficulty: 0,
          isDelete: 0,
          knowledgeId: 0,
          option: '',
          parsing: '',
          score: 0,
          singleId: 0,
          topicId: 0,
          updateTime: ''
        }
      },
      single: {},
      rules: {
       knowledge: [
          {
            required: true,
            message: '请选择作者',
            trigger: 'blur'
          }
        ],
        input: [
          {
            required: true,
            message: '请输入题干',
            trigger: 'blur'
          }
        ],
        // inputss: [{
        // 	required: true,
        // 	message: "请输入解析",
        // 	trigger: "blur"
        // }],
        // option: [{
        // 	required: true,
        // 	message: "请设置选项",
        // 	trigger: "change"
        // }],
        numm: [
          {
            required: true,
            message: '请设置分数',
            trigger: 'blur'
          }
        ],
        difficulty: [
          {
            required: true,
            message: '请设置难度',
            trigger: 'change'
          }
        ],
        type: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个标准答案',
            trigger: 'blur'
          }
        ],
        resource: [
          {
            required: true,
            message: '请选择活动资源',
            trigger: 'change'
          }
        ],
        desc: [
          {
            required: true,
            message: '请填写活动形式',
            trigger: 'blur'
          }
        ]
      },
      options: [],
      valuename: '',
	  knowledges:'',

      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: false, // code
        table: true, // 表格
        fullscreen: false, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: false, // 单双栏模式
        preview: true, // 预览
        toolbarsFlag: false
      },
      blogContent: '',
      blogMdContent: '',
      text: '**chbferbfb**'
    }
  },
  created() {
    this.Inint();
    // this.Inint1()
  },
  methods: {
	md(content) {
		return marked(content);
	},
    changeInput() {
      this.centerDialogVisible = true
    },
    type(e) {
      this.ruleForm.label = e
    },
    removeDomain(item) {
      var index = this.ruleForm.domains.indexOf(item)
      if (index !== -1) {
        this.ruleForm.domains.splice(index, 1)
      }
    },

    addDomain() {
      this.ruleForm.domains.push({
        value: '',
        key: Date.now()
      })
    },
	//添加单选题
    submitForm(formName) {
	  let options = [];
	  this.ruleForm.domains.forEach((item, index) => {
	  	if (index !== this.Indexk) {
	  		options.push({
	  			content: item.value,
	  			isAnswer: false
	  		})
	  	} else {
	  		options.push({
	  			content: item.value,
	  			isAnswer: true
	  		})
	  	}
	  
	  })
	  var data = {
	  	topicId: 1,
	  	content: this.ruleForm.input,
	  	parsing: this.ruleForm.analysis,
	  	difficulty: this.value1,
	  	score: this.num,
	  	optionsList: options
	  }
      
      TestManager.addChoiceQuestion(data,this.valuename)
        .then(res => {
          // this.ruleForm = res
          // 组装题目信息 发给父组件
          const qData= {
            topic: this.ruleForm.input,
            id: res.data.data,
            score: this.num
          };
          console.log(qData)
          this.$emit('addSingle', qData)
          this.open()
          this.resetForm('ruleForm')
        })
    },
    open() {
      this.$alert('添加成功', '成功', {
        confirmButtonText: '确定',
        callback: action => {
          // this.$message({
          //   type: 'info',
          //   message: `action: ${action}`
          // })
        }
      })
    },
    submitFormss(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
      axios.post('/api/question/single/modifySingle', this.single).then(res => {
        this.ruleForm = res
      })
    },
    resetForm(ruleFom) {
      this.$refs[ruleFom].resetFields()
      this.ruleForm.name = ''
      this.ruleForm.input = ''
      this.ruleForm.label = ''
      this.ruleForm.analysis = ''
      this.value1 = null
      this.num = 1
      this.valuename = ''
    },
	//获取知识点树
    Inint() {
		TestManager.getAllKnowledgeTree().then(res=>{
			console.log(res.data.data)
			this.options = res.data.data;
		})
    
    },
	
	//获取知识点
	handleChange(value) {
		console.log(this.valuename);
		this.vals = this.getCascaderObj(value, this.options);
		console.log(this.vals);
		let str='';
		for (var i = 0; i < this.vals.length; i++) {
			console.log(this.vals[i]);
			if(i==this.vals.length-1)
			{
				str+=this.vals[i];
			}else{
				str+=this.vals[i]+'/';
			}
			
			
		}
		this.knowledges=str;
		
	},
	//遍历知识点树
	getCascaderObj(val, opt) {
		return val.map(function(value, index, array) {
			for (var itm of opt) {
				if (itm.value == value) {
					opt = itm.children;
					return itm.label;
				}
			}
			return null;
		});
	}
    
    
  }
}
</script>

<style lang="scss" scoped>
.checkedCities {
  margin-top: 10px;
}

.valuee {
  margin-left: 10px;
}

.value {
  margin-left: 15px;
}

.level {
  display: flex;
  align-items: center;
}

.el-checkbox {
  width: 30px;
}

.typess {
  display: flex;
  width: 30px;
  justify-content: end;
  position: relative;
  top: -15px;
  left: -5px;
  z-index: 1;
}

.single {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;

  .preview {
    margin-top: 20px;
    // margin-left: 20px;
    // position: absolute;
    right: 15px;
    box-shadow: -9px -9px 18px #f3f3f3, 9px 9px 18px #ffffff;

    .title {
      width: 100%;
      // height: 7vh;
      border-bottom: 1px solid #aaa;
      line-height: 7vh;
      padding-left: 20px;
    }

    .text {
      margin-top: 20px;
      padding-left: 20px;
      // width: 40vw;

      div {
        margin-bottom: 5px;
      }

      .analysis {
        margin-bottom: 25px;
      }
    }
  }
}

.frame {
  // width: 90vw;
  height: 100%;
  margin-left: 30px;
  margin-right: 30px;
  margin-top: 20px;
}

.options {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;

  div {
    display: flex;
  }

  .spann {
    display: flex;
    width: 30px;
  }

  .span {
    border: 1px solid #aaa;
    border-radius: 5px;
    display: flex;
    width: 80px;
    height: 39px;
    margin-left: 10px;
    justify-content: center;
  }

  .input {
    margin-left: 10px;
    // width: 50vw;
  }

  .button {
    width: 40px;
    height: 39px;
    background-color: #ff4949;
    color: #fff;
    text-align: center;
    padding-left: 10px;
    margin-left: 10px;
  }
}

.difficulty {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
}

.mavon-editor {
  // width: 80vw;
}
</style>
